from PyQt5.Qt import *
from resource.query import Ui_Form
from API.APItool import APItool
from book_panel import BookPanel


class QueryPanel(QWidget, Ui_Form):
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setAttribute(Qt.WA_StyledBackground, True)
        self.setupUi(self)
        self.setupDate()
        self.setBookPanel()
        self.tj = {"zw": None, "phone_num": None}

    def setupDate(self):
        dic = APItool.getStationName()
        self.form_station_cb.addItems(dic.keys())
        self.to_station_cb.addItems(dic.keys())

        # 设置完成器，输入联想词生成可选择列表
        completer = QCompleter(dic.keys())
        completer2 = QCompleter(dic.keys())
        self.form_station_cb.setCompleter(completer)
        self.to_station_cb.setCompleter(completer2)

        # 结束编辑时，如果用户输入的城市不存在，则会自动清空文字
        # 因为QComboBox自身并没有editingFinished结束编辑信号，但是他由多个控件组成，
        # 其中有LineEdit组成，LineEait有editingFinished信号
        def checkDate(cb):
            current_city = cb.currentText()
            if not dic.keys().__contains__(current_city):  # 判定字典内有没有包含当前输入框的文字
                cb.clearEditText()

        self.form_station_cb.lineEdit().editingFinished.connect(lambda: checkDate(self.form_station_cb))
        self.to_station_cb.lineEdit().editingFinished.connect(lambda: checkDate(self.to_station_cb))

        # 设置日期选择框的日期为当前日期
        self.star_date_de.setDate(QDate.currentDate())
        self.star_date_de.setMinimumDate(QDate.currentDate())

        # 设置表格头部数据
        model = QStandardItemModel(self.tickets_tv)
        # 设置模型头部数据
        header = ["车次", "出发站->到达站", "出发时间->到达时间", "历时", "商务座-特等座", "一等座", "二等座-二等包座", "高级-软卧", "软卧-一等卧", "动卧", "硬卧-二等卧",
                  "硬座", "无座", "其他", "备注"]

        model.setColumnCount(len(header))
        for idx, title in enumerate(header):
            model.setHeaderData(idx, Qt.Horizontal, title)

        self.tickets_tv.setModel(model)

    def queryTickets(self):
        dic = APItool.getStationName()
        print("查询票")
        star_date = self.star_date_de.text()
        print(star_date)
        from_city_code = dic[self.form_station_cb.currentText()]
        to_city_code = dic[self.to_station_cb.currentText()]
        print(from_city_code, to_city_code)
        # 查看按钮组里面的当前被选中的按钮,并取出自定义属性值的内容
        purpose_codes = self.buttonGroup.checkedButton().property("q_value")
        print(purpose_codes)

        result = APItool.queryTickets(star_date, from_city_code, to_city_code, purpose_codes, seat_type=self.tj["zw"])
        print(result)

        model = self.tickets_tv.model()
        model.setRowCount(len(result))
        columns = ["train_name", ("from_station_name", "to_station_name"), ("star_time", "arrive_time"), "total_time",
                   "business_seat", "firsh_seat", "second_seat", "vip_solf_bed", "solf,bed", "move_bed", "hard_bed", "",
                   "hard_seat", "no_seat", "other_seat"]
        for row, train_dic in enumerate(result):
            print(train_dic)
            for column, column_name in enumerate(columns):
                if type(column_name) == str:
                    model.setItem(row, column, QStandardItem(train_dic[column_name]))
                else:
                    # temp=""
                    # for key in column_name:
                    #     temp+=train_dic[key]
                    temp = "->".join([train_dic[key] for key in column_name])
                    model.setItem(row, column, QStandardItem(temp))

        self.tickets_tv.setModel(model)

        return result

    def bookTickets(self):
        self.showBookPanel()
        self.timer=QTimer(self)
        self.timer.timeout.connect(self.buyTcikets)

    def buyTcikets(self):
        # 用户点击确定后，显示筛选有票的
        result = self.queryTickets()
        if len(result) > 0:
            self.cancelQuery()
            print("当前有车票，正在购买")
            success = APItool.buyTicket(result[0])
            if success:
                QMessageBox.information(self,"恭喜","购买成功，快去支付吧！")
            else:
                QMessageBox.warning(self, "很抱歉", "购买失败！")

    def setBookPanel(self):

        self.book_panel = BookPanel(self)
        self.book_panel.confirmSignal.connect(self.bookTicketFilter)
        self.book_panel.cancelSignal.connect(self.cancelQuery)
        # self.book_panel.resize(self.width(), 150)
        self.book_panel.move(0, -150)
        self.book_panel.show()

    def hideBookPanel(self):
        animation = QPropertyAnimation(self.book_panel, b"pos", self.book_panel)
        animation.setEndValue(QPoint(0, -150))
        animation.setStartValue(QPoint(0, 0))
        animation.setDuration(1000)
        animation.setEasingCurve(QEasingCurve.OutBounce)
        animation.start(QAbstractAnimation.DeleteWhenStopped)

    def showBookPanel(self):
        animation = QPropertyAnimation(self.book_panel, b"pos", self.book_panel)
        animation.setStartValue(QPoint(0, -self.query_panel_top.height()))
        animation.setEndValue(QPoint(0, 0))
        animation.setDuration(1000)
        animation.setEasingCurve(QEasingCurve.OutBounce)
        animation.start(QAbstractAnimation.DeleteWhenStopped)

    def bookTicketFilter(self, tj):
        # tj,接收的提交字典
        print(tj)
        self.tj = tj
        self.timer.start(3000)



    def resizeEvent(self, ResizeEvent):
        super().resizeEvent(ResizeEvent)
        self.book_panel.resize(self.width(), self.query_panel_top.height())

    def cancelQuery(self):
        print("取消")
        self.timer.stop()
        self.hideBookPanel()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    window = QueryPanel()
    window.show()
    sys.exit(app.exec_())
